package com.wsc.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.wsc.entity.Teacher;
import com.wsc.service.TeacherService;
import com.wsc.utils.ExportExcelUtil;
import com.wsc.utils.ImportBeanExcel;

@RequestMapping("/teacher")
@RestController
@CrossOrigin
public class TeacherController {
	@Autowired
	private TeacherService ts;

	// 增加
	@RequestMapping("add")
	public Integer add(Teacher t) {
		return ts.add(t);
	}

	// 修改
	@RequestMapping("update")
	public Integer update(Teacher t) {
		return ts.update(t);
	}

	// 单删
	@RequestMapping("deleteById")
	public Integer deleteById(Integer id) {
		return ts.deleteById(id);
	}

	// 多删
	@RequestMapping("deleteByIds")
	public Integer deleteByIds(String ids) {
		// 字符串拆分为Spring类型的数组
		String[] arr = ids.split(",");
		Integer temp = 0;
		// 循环单删
		for (int i = 0; i < arr.length; i++) {
			Integer id = Integer.parseInt(arr[i]);
			temp = ts.deleteById(id);
		}
		return temp;
	}

	// id cardno name sex sectionid status remark
	// 查 多条件 分页
	@RequestMapping("getAll")
	public Map<String, Object> getAll(Teacher teacher, Integer page, Integer limit) {
		Map<String, Object> params = new HashMap<String, Object>();
		// System.out.println(teacher.getStatus());
		params.put("teacher", teacher);
		limit = limit == null ? 10 : limit;
		page = page == null ? 0 : page - 1;
		params.put("limit", limit);
		params.put("page", page);
		// System.out.println(ts.getAll(params).get("data"));
		return ts.getAll(params);
	}

	// 导入
	@RequestMapping("importTeacher")
	public Map<String, Object> importTeacher(MultipartFile file) {
		Map<String, Object> map = new HashMap<String, Object>();
		// Excel有效数据总数（除去标题、表头）
		Integer count = 0;
		// 成功导入的数据总数
		Integer importCount = 0;
		try {
			// 读取excel表格
			List<List<String>> lists = ImportBeanExcel.readExcel(file.getInputStream());
			// 判断集合是否为空 list集合存储的是List<String>类型
			if (!CollectionUtils.isEmpty(lists)) {
				for (int i = 1; i < lists.size(); i++) {
					count = lists.size() - 1;
					// 判断Excel是否首行表名，次行表头，三行数据
					if ("卡号".equals(lists.get(i).get(0))) {
						count--;
						i++;
					}
					List<String> list = lists.get(i);
					// 获取excel表中的数字为Double类型需要转Integer
					// id cardno name sex sectionid status remark
					// 卡号
					String cardno = list.get(0);
					// 姓名
					String name = list.get(1);
					// 性别
					String sex = list.get(2);
					// 身份编号
					Double sectionidD = Double.parseDouble(list.get(3));
					Integer sectionid = new Double(sectionidD).intValue();
					// 状态
					Double statusD = Double.parseDouble(list.get(4));
					Integer status = new Double(statusD).intValue();
					// 备注
					String remark = list.get(5);
					Teacher t = new Teacher(null, cardno, name, sex, sectionid, status, remark, null);
					try {
						// add方法有校验
						importCount += ts.add(t);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			// 导入总数据数量
			map.put("count", count);
			// 导入未重复数据数量
			map.put("importCount", importCount);
		} catch (IOException e) {
			map.put("count", 0);
			map.put("importCount", importCount);
			e.printStackTrace();
		}
		return map;
	}
	// 导出 使用无回调函数提交方式
	@RequestMapping("/exportTeacher")
	public void export(HttpServletRequest request, HttpServletResponse response, String ids) {
		// excel标题
		String title = "教师表";
		// excel表名
		String[] headers = { "卡号", "姓名", "性别", "科室编号", "状态", "备注" };
		// excel文件名
		String fileName = title + System.currentTimeMillis() + ".xls";
		// String转String数组
		String[] arr = ids.split(",");
		// List of Teacher Type
		List<Map<String, Object>> list = new ArrayList<>();
		// HashSet集合去除重复id
		HashSet<Integer> hs = new HashSet<Integer>();
		for (int i = 0; i < arr.length; i++) {
			// String convert Integer
			Integer id = Integer.parseInt(arr[i]);
			// get Teacher Entity
			// 数组元素添加到HashSet去重复
			hs.add(id);
		}
		for (Integer id : hs) {
			Teacher t = ts.getOne(id);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cardno", t.getCardno());
			map.put("name", t.getName());
			map.put("sex", t.getSex());
			map.put("sectionid", t.getSectionid());
			map.put("status", t.getStatus());
			map.put("remark", t.getRemark());
			list.add(map);
		}
		// excel元素
		String content[][] = new String[list.size()][3];
		for (int i = 0; i < list.size(); i++) {
			content[i] = new String[headers.length];
			content[i][0] = list.get(i).get("cardno").toString();
			content[i][1] = list.get(i).get("name").toString();
			content[i][2] = list.get(i).get("sex").toString();
			content[i][3] = list.get(i).get("sectionid").toString();
			content[i][4] = list.get(i).get("status").toString();
			// get(i)和get("key") 必须存在，若不存在即为null，会报NullPointerException
			Object remark = list.get(i).get("remark") == null ? "" : list.get(i).get("remark");
			content[i][5] = remark.toString();
		}
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(title, headers, content);
		// 响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=Utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
